package com.fruit.service.shopping.impl;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.fruit.constants.GoodsConstant;
import com.fruit.mapper.goods.GoodsMapper;
import com.fruit.mapper.order.DshOrderMapper;
import com.fruit.mapper.pay.PayMapper;
import com.fruit.mapper.shopping.ShoppingMapper;
import com.fruit.pojo.common.OperatingConfig;
import com.fruit.pojo.goods.Goods;
import com.fruit.pojo.goods.GoodsTradePrice;
import com.fruit.pojo.order.OrderConfig;
import com.fruit.pojo.shopping.Shopping;
import com.fruit.service.shopping.ShoppingManager;
import com.fruit.util.DateUtil;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;


/** 购物车
 * 修改时间：2016.07.15
 */
@Service("shoppingService")
public class ShoppingService implements ShoppingManager{

	@Autowired
	private ShoppingMapper shoppingMapper;
	
	@Autowired
	private GoodsMapper goodsMapper;
	
	@Autowired
	private PayMapper payMapper;
	
	@Autowired
	private DshOrderMapper dshOrderMapper;
	
	@Override
	public Map<String, Object> createGetShoppingList(int userId) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		List<Shopping> shoppingList = shoppingMapper.getShoppingList(userId);
		if(shoppingList == null || shoppingList.size() == 0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "shopping_empty", "购物车为空!"));
			return resMap;
		}
		List<Shopping> goodsList = new ArrayList<Shopping>();
		Map<String, Object> params = new HashMap<String, Object>();
		int shoppingNum = 0;
		for(Shopping shopping:shoppingList){
			boolean set = false;
			Goods goods = goodsMapper.getGoodsDetail(shopping.getGoodsId());
			if(goods != null && goods.getState().equals(GoodsConstant.STATE_UP)){
				String curTime = DateUtil.getTime();
				if(DateUtil.compareDate2(curTime,goods.getStartTime()) && DateUtil.compareDate2(goods.getEndTime(),curTime)){
					params.clear();
					params.put("goodsId", goods.getId());
					params.put("num", shopping.getNum());
					List<GoodsTradePrice> gtpList = goodsMapper.getGoodsTradePrice(params);
					if(gtpList != null && gtpList.size() == 1){
						set = true;
						GoodsTradePrice gtp = gtpList.get(0);
						shopping.setTradePrice(gtp.getPrice());
						shopping.setTitle(goods.getTitle());
						shopping.setSubTitle(goods.getSubTitle());
						shopping.setThumb(goods.getThumb());
						goodsList.add(shopping);
						shoppingNum += shopping.getNum();
					}
				}
			}
			if(!set){
				//移除购物车
				long ids[] = {shopping.getId()};
				shopping.setIds(ids);
				delShopping(shopping);
			}
		}
		
		if(goodsList == null || goodsList.size() == 0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "shopping_empty", "购物车为空!"));
			return resMap;
		}
		
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "查找成功!"));
		resMap.put("goodsList", goodsList);
		resMap.put("shoppingNum", shoppingNum);
		return resMap;
	}

	
	@Override
	public Map<String, Object> delShopping(Shopping shopping) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		if(shopping.getIds() == null || shopping.getIds().length ==0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "params_error", "参数错误!"));
			return resMap;
		}
		int num = shoppingMapper.delShopping(shopping);
		if(num == 0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "faile", "失败!"));
			return resMap;
		}
		
		int shoppingNum = shoppingMapper.getShoppingNumber(shopping.getUserId());
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "修改成功!"));
		resMap.put("shoppingNum", shoppingNum);
		return resMap;
	}



	@Override
	public Map<String, Object> addShopping(Shopping shopping) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		int res = 1;
		try{
		//验证参数
		if(shopping.getGoodsId() <= 0 
				|| shopping.getNum() <= 0 
				|| StringUtils.isEmpty(shopping.getSpec()) 
				|| StringUtils.isEmpty(shopping.getUnit())){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "params_error", "参数错误!"));
			return resMap;
		}
		
		Shopping shoppingr = shoppingMapper.getShoppingByGId(shopping);
		if(shoppingr != null){
			shopping.setId(shoppingr.getId());
			shopping.setNum(shopping.getNum()+shoppingr.getNum());
			resMap = updateShopping(shopping);
			return resMap;
		}else{
			//判断购物车数量上限
			List<OrderConfig> orderConfigList = dshOrderMapper.getOrderConfig();
			if(orderConfigList == null || orderConfigList.size() != 1){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception_order_config", "系统繁忙!"));
				return resMap;
			}
			int shoppingCnt = shoppingMapper.getShoppingCnt(shopping.getUserId());
			OrderConfig orderConfig = orderConfigList.get(0);
			if(shoppingCnt >= orderConfig.getShoppingMaxNum()){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "shopping_max", "购物车数量已达到上限，请先结算购物车!"));
				return resMap;
			}
			
			//判断是否存在	
			Goods goods = goodsMapper.getGoodsDetail(shopping.getGoodsId());
			if(goods == null || !GoodsConstant.STATE_UP.equals(goods.getState())){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "goods_no_exists", "购物车商品不存在!"));
				return resMap;
			}
			
			String curTime = DateUtil.getTime();
			if(!(DateUtil.compareDate2(curTime,goods.getStartTime()) && DateUtil.compareDate2(goods.getEndTime(),curTime))){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "goods_no_exists", "商品（"+goods.getTitle()+"）未上架或已下架!"));
				return resMap;
			}	
			
			List<OperatingConfig> ocList = payMapper.getOperatingConfig();
			if(ocList != null && ocList.size() ==1){
				OperatingConfig oc = ocList.get(0);
				long hsmTime = DateUtil.getHsmTime();
				
				if(hsmTime < oc.getMinTime() || hsmTime > oc.getMaxTime()){
					resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "operating_error", "已过运营时间!"));
					return resMap;
				}
	
			}
			
			
			List<Shopping> shoppingList = shoppingMapper.getShoppingList(shopping.getUserId());
			if(shoppingList != null && shoppingList.size() >=10){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "shopping_full", "购物车数量已达到上限，请先清理购物车!"));
				return resMap;
			}
			
			//商品单位换算
			if(!StringUtils.equals(shopping.getUnit(), goods.getUnit())){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "unit_error", "单位错误!"));
				return resMap;
			}
			int unitNum = shopping.getNum();
			if(goods.getStockNum() < unitNum){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "goods_stock_full", "商品（"+goods.getTitle()+"）库存不足!"));
				return resMap;
			}
			
			shopping.setCreateTime(DateUtil.getTime());
			shopping.setUpdateTime(DateUtil.getTime());
			shoppingMapper.addShopping(shopping);
			
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("goodsId", goods.getId());
			params.put("num", shopping.getNum());
			List<GoodsTradePrice> gtpList = goodsMapper.getGoodsTradePrice(params);
			if(gtpList == null || gtpList.size() > 1 || gtpList.size() == 0){
				res = 0;
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "price_error", "金额错误!"));
				return resMap;
			}
			int shoppingNum = shoppingMapper.getShoppingNumber(shopping.getUserId());
			resMap.put("shoppingNum", shoppingNum);
			resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "添加成功!"));
			return resMap;
		}
		}finally{
			if(res == 0){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}
		
	}



	@Override
	public Map<String, Object> updateShopping(Shopping shopping) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		int res = 1;
		try{
		int num = shopping.getNum();
		
		if(num <= 0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "params_error", "参数错误!"));
			return resMap;
		}
		Shopping shoppingr = shoppingMapper.getShoppingById(shopping.getId());
		if(shoppingr == null){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "shopping_no_exists", "购物车商品不存在!"));
			return resMap;
		}
		Goods goods = goodsMapper.getGoodsDetail(shoppingr.getGoodsId());
		if(goods == null || !GoodsConstant.STATE_UP.equals(goods.getState())){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "goods_no_exists", "购物车商品已下架!"));
			return resMap;
		}
		String curTime = DateUtil.getTime();
		if(!(DateUtil.compareDate2(curTime,goods.getStartTime()) && DateUtil.compareDate2(goods.getEndTime(),curTime))){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "goods_no_exists", "商品（"+goods.getTitle()+"）未上架或已下架!"));
			return resMap;
		}	
		
		List<OperatingConfig> ocList = payMapper.getOperatingConfig();
		if(ocList != null && ocList.size() ==1){
			OperatingConfig oc = ocList.get(0);
			long hsmTime = DateUtil.getHsmTime();
			
			if(hsmTime < oc.getMinTime() || hsmTime > oc.getMaxTime()){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "operating_error", "已过运营时间!"));
				return resMap;
			}

		}
		
		//商品单位换算
		if(!StringUtils.equals(shopping.getUnit(), goods.getUnit())){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "unit_error", "单位错误!"));
			return resMap;
		}
		int unitNum = shopping.getNum();
		if(goods.getStockNum() < unitNum){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "goods_stock_full", "商品（"+goods.getTitle()+"）库存不足!"));
			return resMap;
		}
		shoppingr.setNum(num);
		int updateResult = shoppingMapper.updateShoppingNum(shoppingr);
		if(updateResult == 0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "faile", "失败!"));
			return resMap;
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("goodsId", goods.getId());
		params.put("num", shoppingr.getNum());
		List<GoodsTradePrice> gtpList = goodsMapper.getGoodsTradePrice(params);
		if(gtpList == null || gtpList.size() > 1 || gtpList.size() == 0){
			res = 0;
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "price_error", "金额错误!"));
			return resMap;
		}
		resMap.put("tradePrice", gtpList.get(0).getPrice());
		int shoppingNum = shoppingMapper.getShoppingNumber(shopping.getUserId());
		resMap.put("shoppingNum", shoppingNum);
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "修改成功!"));
		return resMap;
		}finally{
			if(res == 0){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}
	}


	@Override
	public Map<String, Object> getShoppingNum(Shopping shopping) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		int shoppingNum = shoppingMapper.getShoppingNumber(shopping.getUserId());
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "success", "查询成功!"));
		resMap.put("number", shoppingNum);
		return resMap;
	}


	
}
